<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useGetClassificationsService } from '../api/task'
import { useUserStore } from '../stores/modules/user'
const userStore = useUserStore()

// 分类清单列表
const classifyList = ref([])
// 获取分类清单列表
const getClassifications = async () => {
  const res = await useGetClassificationsService({ user_id: userStore.userId })
  console.log('编辑对话框中从后端获取的分类列表res:', res)
  classifyList.value = res.data.data
}
onMounted(() => {
  getClassifications()
})
// 添加处理分类变化的方法
// 这里classifyName自动获取到item.classify_name
const handleClassifyChange = (classifyName: string) => {
  const selectedClassify = classifyList.value.find(item => item.classify_name === classifyName)
  if (selectedClassify) {
    form.value.classify_id = selectedClassify.id
    form.value.classify_name = classifyName
    console.log('选择分类:', { 
      id: selectedClassify.id, 
      name: classifyName 
    })
  } else {
    form.value.classify_id = 0
    form.value.classify_name = ''
  }
}
// 接收父组件传来的editCardVisible
const props = defineProps({
  editCardVisible: Boolean,  // 编辑框显隐
  formData: Object,  // 表单数据
  addTask: Function,  // 添加任务事件
  defaultClassifyName: String,  // 默认分类名称
})
// 定义emit
const emit = defineEmits(['update:editCardVisible', 'update:formData', 'confirm'])
// 控制编辑框显隐
const dialogVisible = ref(props.editCardVisible)
// 表单标签宽度
const formLabelWidth = '140px'
// 表单数据
const form = ref(props.formData)
const getDate = (dateTime) => {
  form.value.finishDate = dateTime
  console.log('获取时form.value.finishDate' + form.value.finishDate)
}
// 处理取消事件
const handleCancel = () => {
  dialogVisible.value = false
  form.value.title = ''
  form.value.classify_id = ''
  form.value.classify_name = ''
  form.value.finishDate = ''
}
// 处理确认事件
const handleConfirm = () => {
  dialogVisible.value = false
  if (!form.value.title?.trim()) {
    ElMessage.warning('任务标题不能为空')
    return
  }
  emit('update:formData', form.value)
  // 触发确认事件，添加任务
  // 表示通知父组件添加任务，遵循“谁的数据谁负责”的原则
  emit('confirm', form.value.id)  // 将id传给父组件，因为编辑任务时需要传入id 
  // 清空表单数据
  form.value = {
    title: '',
    classify_id: '',
    classify_name: '',
    finishDate: '',
  }
}
// 监听父组件传来的editCardVisible，实时更新dialogVisible
watch(() => props.editCardVisible, (newVal) => {
  dialogVisible.value = newVal
})
// 监听dialogVisible，实时更新父组件的editCardVisible
watch(dialogVisible, (newVal) => {
  emit('update:editCardVisible', newVal)
})
// 监听从父组件拿到的formData，检查执行编辑事件时是否拿到回显数据
// watch(props.formData, (newVal) => {
//   console.log('从父组件拿到的formData' + JSON.stringify(props.formData))
//   console.log('父组件formData更新后的newVal' + JSON.stringify(newVal))
//   // form.value = newVal
//   form.value = props.formData
//   console.log('拿到父组件formData的form' + JSON.stringify(form.value))
// },{
//   immediate: true,
//   deep: true
// })
watch(
  () => props.formData,
  (newVal) => {
    console.log('从父组件拿到的formData:', JSON.stringify(newVal))
    form.value = { ...newVal } // 深拷贝父组件的 formData
    if (!form.value.classify_name && props.defaultClassifyName) {
      form.value.classify_name = props.defaultClassifyName // 如果没有分类名称，则设置默认值
    }
    console.log('拿到父组件formData的form:', JSON.stringify(form.value))
    console.log('拿到父组件formData的props.defaultClassifyName:', props.defaultClassifyName)
  },
  {
    immediate: true,
    deep: true
  }
)
</script>

<template>
  <el-dialog v-model="dialogVisible" title="编辑待办任务" width="500">
    <el-form :model="form">
      <el-form-item label="任务标题" :label-width="formLabelWidth">
        <el-input v-model.trim="form.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="分类" :label-width="formLabelWidth">
        <el-select 
        v-model="form.classify_name" 
        placeholder="选择任务分类(可不选)"
        @change="handleClassifyChange"
        >
          <el-option
          v-for="item in classifyList"
          :key="item.id"
          :label="item.classify_name" 
          :value="item.classify_name" />
        </el-select>
      </el-form-item>
      <el-form-item label="完成时间" :label-width="formLabelWidth">
        <DatePicker 
        v-model="form.finishDate" 
        @input-date="getDate"
        :visible="dialogVisible"
        :finishDate="formData.finishDate"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>